﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using Microsoft.SharePoint;
using System.Data;
using SIMSProject.Common;
using System.IO;
using org.in2bits.MyXls;

namespace SIMSProject.Views.Report.InventoryReport
{
    public partial class InventoryReportUserControl : UserControl
    {
        private DataTableWrapper myDataTable;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
            {
                LoadData();
            }

            this.btExport.OnClientClick = "_spFormOnSubmitCalled = false;_spSuppressFormOnSubmitWrapper=true;";
        }

        private void LoadData()
        {
            if (Session["sourceTable"] != null)
            {
                DataTable sourceTable = (DataTable)Session["sourceTable"];
                myDataTable = new DataTableWrapper(sourceTable);
                Type t = myDataTable.GetType();

                ObjectDataSource ds = new ObjectDataSource();
                ds.ID = "myDataSource";
                ds.TypeName = t.AssemblyQualifiedName;
                ds.SelectMethod = "GetTable";
                ds.ObjectCreating += new ObjectDataSourceObjectEventHandler(ds_ObjectCreating);
                tdGridContainer.Controls.Add(ds);

                grdResult.DataSourceID = "myDataSource";
                grdResult.PageIndexChanging += new GridViewPageEventHandler(oGrid_PageIndexChanging);

                this.btExport.Visible = true;
                this.btExportExcel.Visible = true;
            }
        }

        protected void btShowMaterialReport_Click(object sender, EventArgs e)
        {
            if (this.fromDate.SelectedDate > this.toDate.SelectedDate)
            {
                this.lblValidateText.Visible = true;
                this.lblValidateText.Text = "The to date must greater than from date";
                return;
            }
            else 
            {
                this.lblValidateText.Visible = false;
            }

            // Get available tracking by date
            SPQuery query = new SPQuery();
            query.Query = @"<Where>
                              <And>
                                 <Geq>
                                    <FieldRef Name='Created' />
                                    <Value Type='DateTime'>"+this.fromDate.SelectedDate.ToString("yyyy-MM-dd")+@"</Value>
                                 </Geq>
                                 <Leq>
                                    <FieldRef Name='Created' />
                                    <Value Type='DateTime'>"+this.toDate.SelectedDate.ToString("yyyy-MM-dd")+@"</Value>
                                 </Leq>
                              </And>
                           </Where>";

            SPListItemCollection trackingItems = SPContext.Current.Web.Lists["Material Tracking"].GetItems(query);

            if (trackingItems.Count > 0)
            {
                this.lblResultText.Visible = false;
                this.btExport.Visible = true;
                this.btExportExcel.Visible = true;

                DataTable sourceTable = new DataTable();
                sourceTable.Columns.Add("Number", typeof(string));
                sourceTable.Columns.Add("Date", typeof(string));
                sourceTable.Columns.Add("MaterialCode", typeof(string));
                sourceTable.Columns.Add("MaterialName", typeof(string));
                sourceTable.Columns.Add("Type", typeof(string));
                sourceTable.Columns.Add("Quantity", typeof(string));
                sourceTable.Columns.Add("TypeOfUnit", typeof(string));
                sourceTable.Columns.Add("Position", typeof(string));

                foreach (SPListItem item in trackingItems)
                {
                    SPQuery query2 = new SPQuery();
                    query2.Query = @"<Where>
                                      <Eq>
                                         <FieldRef Name='Title' />
                                         <Value Type='Text'>"+item.ID+@"</Value>
                                      </Eq>
                                   </Where>";

                    SPListItemCollection trackingDetailItems = SPContext.Current.Web.Lists["Material Tracking Detail"].GetItems(query2);
                    foreach (SPListItem item1 in trackingDetailItems)
                    {
                        SPListItem material = SPContext.Current.Web.Lists["Material"].GetItemById(Convert.ToInt32(Convert.ToString(item1["Material Id"])));
                        DataRow row = sourceTable.NewRow();
                        row["Number"] = sourceTable.Rows.Count + 1;
                        row["Date"] = Convert.ToDateTime(Convert.ToString(item["Created"])).ToString("dd-MM-yyyy");
                        row["MaterialCode"] = item1["Material Code"];
                        row["MaterialName"] = item1["Material Name"];
                        row["Type"] = item["Tracking Type"];
                        row["Quantity"] = item1["Quantity"];
                        row["TypeOfUnit"] = material["Type of unit"];
                        row["Position"] = material["Position"];
                        sourceTable.Rows.Add(row);
                    }
                }

                Session["sourceTable"] = sourceTable;
                myDataTable = new DataTableWrapper(sourceTable);
                Type t = myDataTable.GetType();

                ObjectDataSource ds = new ObjectDataSource();
                ds.ID = "myDataSource";
                ds.TypeName = t.AssemblyQualifiedName;
                ds.SelectMethod = "GetTable";
                ds.ObjectCreating += new ObjectDataSourceObjectEventHandler(ds_ObjectCreating);

                if (tdGridContainer.FindControl("myDataSource") !=null)
                {
                    tdGridContainer.Controls.Remove(tdGridContainer.FindControl("myDataSource"));
                }
                tdGridContainer.Controls.Add(ds);

                grdResult.DataSourceID = "myDataSource";
                grdResult.PageIndexChanging += new GridViewPageEventHandler(oGrid_PageIndexChanging);
            }
            else
            {
                this.tSearchResult.Visible = false;
                this.lblResultText.Visible = true;
            }
        }

        void ds_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            DataTable sourceTable = (DataTable)Session["sourceTable"];
            myDataTable = new DataTableWrapper(sourceTable);
            e.ObjectInstance = myDataTable;
        }

        void oGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            DataTable sourceTable = (DataTable)Session["sourceTable"];
            grdResult.PageIndex = e.NewPageIndex;
            grdResult.DataBind();
        }

        protected void btExport_Click(object sender, EventArgs e)
        {
            DataTable dataToExport = (DataTable)Session["sourceTable"];
            if (dataToExport.Rows.Count == 0)
                return;

            Stream file = Utils.ExportToPdf(dataToExport, "Material Tracking Report", new[] { 100, 100, 100, 100, 100, 100, 100, 100 }, DateTime.Now.ToString("dd-MM-yyyy"), SPContext.Current.Web.CurrentUser.Name);

            var buffer = new byte[8192];

            file.Seek(0, SeekOrigin.Begin);
            Response.ClearContent();
            Response.ClearHeaders();
            Response.BufferOutput = true;
            string fileName = string.Format("{0}{1}.pdf", "MaterialTrackingReport_", DateTime.Now.ToString("dd_MM_yyy_h_mm_ss"));
            Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
            Response.ContentType = "application/pdf";

            int bytesRead = file.Read(buffer, 0, 8192);
            while (bytesRead > 0)
            {
                var buffer2 = new byte[bytesRead];
                Buffer.BlockCopy(buffer, 0, buffer2, 0, bytesRead);
                Response.BinaryWrite(buffer2);
                Response.Flush();
                bytesRead = file.Read(buffer, 0, 8192);
            }
            Response.End();
            file.Close();
        }

        protected void btExportExcel_Click(object sender, EventArgs e)
        {
            string fileName = string.Format("{0}{1}.xls", "MaterialReport_", DateTime.Now.ToString("dd_MM_yyy_h_mm_ss"));
            string sheetName = fileName.Replace(".xls", "");

            DataTable dataToExport = (DataTable)Session["sourceTable"];
            if (dataToExport.Rows.Count == 0)
                return;

            string[] docHeader = { "Number", "Date", "Material Code", "Material Name", "Type", "Quantity", "Type Of Unit", "Position" };

            XlsDocument doc = Utils.ExportToExcel(fileName, sheetName, dataToExport, docHeader, "Material Tracking Report","", "");
            doc.Send();
            Response.Flush();
            Response.End();
        }
    }
}
